package com.docman.controller;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.docman.dao.UserDAO;
import com.docman.domainmodel.DepartmentBean;
import com.docman.domainmodel.UniversityBean;
import com.docman.domainmodel.UserBean;
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
 
    public RegisterServlet() {
        super();
       
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("text/html;  charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		
		UserBean user = new UserBean();
		
		String userName = request.getParameter("username");
		String firstName = request.getParameter("firstname");
		String lastName = request.getParameter("lastname");
		String email = request.getParameter("email");
		String password = request.getParameter("password1");
		String verifyPass = request.getParameter("password2");
		String question = request.getParameter("question");
		String answer = request.getParameter("answer");
		String university = request.getParameter("university");
		String dept = request.getParameter("department");
		
	
		System.out.println("Register Servlet" + userName + " "+ university + " " + dept);
		
		if(firstName != null && firstName != "" ){
			user.setFirstName(firstName);
		}
		if(lastName != null && lastName != "" ){
			user.setLastName(lastName);
		}
		if(userName != null && userName != "" ){
			user.setUserName(userName);
		}
		if(email != null && email != "" ){
			user.setEmail(email);
		}
		if((password != null && password != "") && (password.equals(verifyPass)) ){
			try {
				MessageDigest md = MessageDigest.getInstance("SHA-256");
				 md.update(password.getBytes());
				 
			        byte byteData[] = md.digest();
			 
			        //convert the byte to hex format method 1
			        StringBuffer sb = new StringBuffer();
			        for (int i = 0; i < byteData.length; i++) {
			         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
			         password = sb.toString();
			        }
			} catch (NoSuchAlgorithmException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			user.setPassword(password);
		}
		if(question != null && question != ""){
			user.setQuestion(question);
		}
		if(answer != null && answer != ""){
			user.setAnswer(answer);
		}
		if(university != null && university != ""){
			UniversityBean uni = new UniversityBean();
			uni.setUniversityName(university);
			user.setUniversity(uni);
		}
		if(dept != null && dept != ""){
			DepartmentBean department = new DepartmentBean();
			department.setDepartmentName(dept);
			user.setDepartment(department);
		}
		
		System.out.println(user.toString());
		
		if(user.getFirstName()==null || user.getLastName()==null || user.getPassword()==null || user.getUserName()==null || user.getEmail()==null){
			response.sendRedirect("register.jsp");
		}
		else{
		
			boolean error= false;
			
		try {
			UserDAO.register(user);
			}
		 catch (com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException e) {
			System.out.println("exception in servlet "+e);
			request.setAttribute("error", "Geçersiz kullanıcı adı veya mail adresi, lütfen tekrar deneyiniz.");
			//e.printStackTrace();
			 error=true;
		}
		
		//System.out.println(user.getUserName()+user.getFirstName()+user.getLastName()+user.getPassword()+user.getEmail());
		if(!error){
		response.sendRedirect("index.jsp");
		} else{
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/getUniandDeptServletpath");
			dispatcher.forward(request, response);
		}		
		}
	}

}
